﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ERP.Domain.System;
using System.Repository.Interface;
using Common.Communal;
using System.Services.Organizes;

namespace System.Services.Organizes
{
    public class OrganizeService:IOrganizeService
    {
        /// <summary>
        /// 组织仓储接口
        /// </summary>
        private readonly IOrganizeRepository _organizeRepository;
        /// <summary>
        /// 构造函数，注入组织仓储接口
        /// </summary>
        /// <param name="organizeRepository">组织仓储接口</param>
        public OrganizeService(IOrganizeRepository organizeRepository)
        {
            _organizeRepository = organizeRepository;
        }
        /// <summary>
        /// 添加组织
        /// </summary>
        /// <param name="organize">组织实体</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Add(Organize organize)
        {
            var result = new ApiResult<int>();
            try
            {
                // 参数验证
                if (organize == null)
                {
                    result.Error(result.Message = "组织信息不能为空");
                    return result;
                }

                // 验证组织编号
                if (string.IsNullOrWhiteSpace(organize.OrganizeNo))
                {
                    result.Error(result.Message = "组织编号不能为空");
                    return result;
                }

                if (organize.OrganizeNo.Length > 50)
                {
                    result.Error(result.Message = "组织编号长度不能超过50个字符");
                    return result;
                }

                // 验证组织名称
                if (string.IsNullOrWhiteSpace(organize.OrganizeName))
                {
                    result.Error(result.Message = "组织名称不能为空");
                    return result;
                }

                if (organize.OrganizeName.Length > 100)
                {
                    result.Error(result.Message = "组织名称长度不能超过100个字符");
                    return result;
                }

                // 验证组织类型
                if (string.IsNullOrWhiteSpace(organize.OrganizeTypeNo))
                {
                    result.Error(result.Message = "组织类型不能为空");
                    return result;
                }
                // 检查组织编号是否已存在
                var no = await _organizeRepository.GetAsync(x => x.OrganizeNo == organize.OrganizeNo&&x.IsDeleted==false);
                if (no.Count() > 0)
                {
                    result.Error(result.Message = "组织编号已存在");
                    return result;
                }
                var code = await _organizeRepository.GetAsync(x => x.Id == organize.ParentId&&x.IsDeleted==false);
                if (code.Count() == 0)
                {
                    // 顶级组织没有父级
                    organize.ParentId = null;
                    // 顶级组织层级为1
                    organize.Level = 1;
                }
                else
                {
                    var codes = code.FirstOrDefault();
                    // 设置层级
                    organize.Level = codes.Level + 1;
                }
                // 添加组织
                var res = await _organizeRepository.AddAsync(organize);

                if (res > 0)
                {
                    result.Success(res, result.Message = "组织添加成功");
                }
                else
                {
                    result.Error(result.Message = "组织添加失败");
                }
            }
            catch (Exception ex)
            {
                result.Error($"添加组织时发生错误：{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 更新组织
        /// </summary>
        /// <param name="organize">组织实体</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Update(Organize organize)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {

                if (organize.OrganizeNo.Length > 50)
                {
                    result.Error(result.Message = "组织编号长度不能超过50个字符");
                    return result;
                }

                if (organize.OrganizeName.Length > 100)
                {
                    result.Error(result.Message = "组织名称长度不能超过100个字符");
                    return result;
                }
                var code = await _organizeRepository.GetAsync(x => x.Id == organize.ParentId && x.IsDeleted == false);
                if (code.Count() == 0)
                {
                    // 顶级组织没有父级
                    organize.ParentId = null;
                    // 顶级组织层级为1
                    organize.Level = 1;
                }
                else
                {
                    var codes = code.FirstOrDefault();
                    // 设置层级
                    organize.Level = codes.Level + 1;
                }
                // 更新组织
                var res = await _organizeRepository.Update(organize);

                if (res > 0)
                {
                    result.Success(res, result.Message = "组织更新成功");
                }
                else
                {
                    result.Error(result.Message = "组织更新失败");
                }
            }
            catch (Exception ex)
            {
                result.Error($"更新组织时发生错误：{ex.Message}");
            }

            return result;
        }

        /// <summary>
        /// 逻辑删除组织
        /// </summary>
        /// <param name="id">组织ID</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Delete(int id)
        {
            var result = new ApiResult<int>();
            try
            {
                // 检查组织是否存在
                var ids = await _organizeRepository.GetAsync(x => x.Id == id);

                var organize = ids.FirstOrDefault();   

                // 检查是否有子组织（如果存在子组织，则不能删除）
                var list = await _organizeRepository.GetAsync(x => x.ParentId == id && !x.IsDeleted);
                if (list.Count() > 0)
                {
                    result.Error(result.Message = "该组织下存在子组织，不能删除");
                    return result;
                }

                // 执行逻辑删除（设置 IsDeleted 为 true）
                organize.IsDeleted = true;
                var res = await _organizeRepository.Update(organize);

                if (res > 0)
                {
                    result.Success(res, result.Message = "组织删除成功");
                }
                else
                {
                    result.Error(result.Message = "组织删除失败");
                }
            }
            catch (Exception ex)
            {
                result.Error($"删除组织时发生错误：{ex.Message}");
            }

            return result;
        }
    }
}
